Ext.require([ 'Ext.tree.*', 'Ext.data.*', 'Ext.layout.container.HBox', 'Ext.dd.*', 'Ext.window.MessageBox' ]);

Ext.grid.feature.Summary.override({
	generateSummaryData : function() {
		if (this.view.store.totalCount == 0) {
			var sumMap = {};
			var columns = this.view.grid.columns;
			for ( var i in columns) {
				if (columns[i].summaryType == "sum") {
					var dataindex = columns[i].dataIndex;
					sumMap[dataindex] = '';
				}
			}
			this.view.store.getProxy().reader.rawData[this.remoteRoot] = sumMap;
		}
		return this.view.store.getProxy().reader.rawData[this.remoteRoot];
	}
});

var code = null;
var q_select_condition = null;
var unit = 1;
var q_id = null;
var is_page = 0;
var is_openrun = 0;
var q_issum = 0;
var q_title = null;
var is_button = 1;
var conditionItems = new Array();
var fieldList = {};
var columns = new Array();
var url = {};
var urlType = {};
var urlParam = new Array();
var url_field = {};
var querySql = null;
var deep = 1;
var deepcount = 1;
var q_is_title = 1;
var upFlag = true;
var rownumberer = true;
var printConfig = "";
var requestUrl = "";
var menuCode = "";
var condition = {};
var q_condition = null;
var sqlDebug = 0;
var exportLevel = 1;
var qRemark = null;
var q_note = null;
var sortableColumns = true;
var isLocalStorage = true;
var enableLocking = true;
var enableColumnHide = false;
var isSpaceTrans = 1;// 是否处理数据中的空格 0 不处理 1处理
var stripeRows = true;
var gnsqUrl = "";
var gnsqName = "";
var iflfptmof = 0;
var orderCheck = 100000;
// 级联组件初始化赋值数组
var relationConditionArr = [];
// 合计行位置
var summaryPosstion = "bottom";
var compare = false;
//关闭进度条弹出框
var closeProgressShow = false;
function initReportQuery(q_code, q_condition, closeHidden) {
	var paramShow = '0';
	conditionItems = new Array();
	columns = new Array();
	url = {};
	urlType = {};
	urlParam = new Array();
	is_newline = {};
	url_field = {};
	return initReportQueryPanel(q_code, q_condition, closeHidden, paramShow);
};

function initReportQueryPanel(q_code, q_condition, closeHidden, paramShow) {
	code = q_code;
	// condition = q_condition;
	loadReport(code, q_condition, paramShow);
	var panel = initPanel();
	if (conditionItems.length == 0) {
		Ext.ComponentQuery.query('button#report_query_search')[0].setHidden(true);
	}
	if (closeHidden == 'hidden') {
		Ext.ComponentQuery.query('button#report_query_close')[0].setHidden(true);
	}
	if (is_button == 1) {
		Ext.ComponentQuery.query('button[name="screen"]')[0].setHidden(true);
		Ext.ComponentQuery.query('button#report_query_return')[0].setHidden(true);
	} else {
		Ext.ComponentQuery.query('button[name="screen"]')[0].setHidden(true);
		Ext.ComponentQuery.query('button#report_query_return')[0].setHidden(true);
	}

	if (exportLevel == 0) {
		Ext.ComponentQuery.query('button[name="export"]')[0].setHidden(true);
		Ext.ComponentQuery.query('button[name="print"]')[0].setHidden(true);
	} else {
		Ext.ComponentQuery.query('button[name="export"]')[0].setHidden(false);
		Ext.ComponentQuery.query('button[name="print"]')[0].setHidden(false);
	}

	if (!!!qRemark) {
		Ext.ComponentQuery.query('button#report_query_remark')[0].setHidden(true);
	}
	if (iflfptmof == 1 && !isNull(gnsqUrl)) {
		Ext.ComponentQuery.query('button#report_query_gnsq')[0].setHidden(false);
		Ext.ComponentQuery.query('button#report_query_gnsq')[0].setText(gnsqName);
	}

	// fieldConf(fieldList);
	// var reportGrid = DSYGrid.getGrid('reportQueryGrid'+q_code);
	// reportGrid.reconfigure(null,columns);
	// Ext.resumeLayouts(true);
	if (is_openrun == 1) {
		// setTimeout(function () {
		reloadStore(true);
		// }, 100);
	}
	;
	return panel;
};

function loadReport(code, q_condition, paramShow) {
	condition = {};
	fieldList = {};
	Ext.Ajax.request({
		method : 'POST',
		url : "/sys-report/getReportQueryData",
		params : {
			code : code
		},
		async : false,
		success : function(response, options) {
			// 获取返回的JSON，并根据gridid，获取表头配置信息
			var respText = Ext.util.JSON.decode(response.responseText);
			unit = respText.unit;
			is_page = respText.isPage;
			is_openrun = respText.isOpenrun;
			q_id = respText.qId;
			q_issum = respText.qissum;
			q_title = respText.qTitle;
			q_is_title = respText.q_is_title;
			is_button = respText.isButton;
			exportLevel = respText.exportLevel;
			qRemark = respText.remark;
			q_note = respText.q_note;
			if (iflfptmof == 1) {
				gnsqUrl = respText.gnsqUrl;
				gnsqName = respText.gnsqName;
			}
			condition = eval(respText.conditionList);
			fieldList = eval(respText.fieldList);
			conditionConf(condition, q_condition, paramShow);
			fieldConf(fieldList);
		},
		failure : function(response, options) {
			Ext.MessageBox.minWidth = 120;
			Ext.Msg.alert('提示', '获取报表配置信息失败！');
		}
	});
};

function initPanel() {
	var panel = new Ext.panel.Panel({
		itemId : 'reportQueryPanel',
		layout : {
			type : 'vbox',
			align : 'stretch',
			flex : 1
		},
		height : '100%',
		width : '100%',
		border : false,
		dockedItems : [ {
			xtype : 'toolbar',
			dock : 'top',
			itemId : 'contentPanel_toolbar',
			items : items
		} ],
		items : [ initSelect(), initGridPanel() ]
	});
	return panel;
};

/**
 * 初始化右侧主表格
 */
function initSelect() {
	var formPanel = new Ext.form.Panel({
		width : '100%',
		// xtype: "form",
		itemId : 'condition',
		autoScroll : true,
		// flex: 1,
		maxHeight : 150,// 查询区显示4行
		minHeight : 0,
		layout : 'column',
		border : false,
		frame : false,
		defaults : {
			labelAlign : "right",
			xtype : "textfield",
			labelWidth : 100,
			flex : 1,
			columnWidth : 0.32,
			margin : 1
		},
		items : conditionItems
	});
	return formPanel;
};

/**
 * 初始化右侧panel，放置表格
 */
function initGridPanel() {
	var gridPanel =  Ext.create('Ext.panel.Panel', {
		height : '100%',
		flex : 8,
		itemId : 'reportQueryGridPanel',
		layout : {
			type : 'vbox',
			align : 'stretch',
			flex : 1
		},
		border : false,
		items : []
	});
	 // 延迟执行InitGrid方法
	Ext.defer(function() {
		var queryGrid = Ext.ComponentQuery.query('#reportQueryGrid'+q_code);
		if(queryGrid&&queryGrid.length>0){
			queryGrid[0].destroy();
		}
        gridPanel.add(initGrid());
    }, 10);

    return gridPanel;
};

/**
 * 初始化右侧主表格
 */
function initGrid() {
	var titleHidden = false;
	if (q_is_title == 0) {
		titleHidden = true;
	}
	var config = {
		itemId : 'reportQueryGrid' + q_code,
		headerConfig : {
			headerJson : columns,
			columnCls : 'normal',// 查询报表支持表头换行
			columnAutoWidth : false
		},
		header : {
			xtype : 'header',
			title : '<span class="header-font">' + q_title + '</span>',
			itemId : 'condition_header',
			baseCls : 'x-panel-header-new',
			height : 40,
			titleAlign : 'center',
			hidden : titleHidden,
			margin : '0 0 0 0',
			padding : '0 0 0 0'
		},
		checkBox : false,
		rowNumber : true,
		border : true,
		autoLoad : false,
		width : '100%',
		flex : 1,
		dataUrl : '/sys-report/getGridData',
		sortableColumns : eval(sortableColumns),
		isLocalStorage : eval(isLocalStorage),
		enableLocking : eval(enableLocking),
		enableColumnHide:eval(enableColumnHide),
		pageConfig : {
			enablePage : getPage(is_page),
			pageNum : true,
			pageSize : 50
		},
		viewConfig : {
			// 在表格中显示斑马线
			stripeRows: stripeRows,
			// deferEmptyText: true,
			// emptyText: "<div class='empty-text-tip'><img src='/report/image/sysbutton/reportDataEmpty.jpeg' width='160' height='160'><div style='padding: 14px'>亲，没有更多数据了！</div></div>"
		},
		listeners:{
			columnhide: function ( ct, column, eOpts ) {
				if(ct.enableColumnHide){
					if(ct.grid.ownerGrid.enableLocking){
	            		var saveColumns = new Array();
	                	if(ct.grid.ownerGrid.isLocalStorage && DSYGrid.getLocalStorageFlag(ct.grid.ownerGrid.columns)){
	                		var lockedColumns = ct.grid.ownerGrid.lockedGrid.getColumns();
	                		var normalColumns = ct.grid.ownerGrid.normalGrid.getColumns();
	                		var saveItemId = ct.grid.ownerGrid.itemId;
	                		for(var i in lockedColumns){
	                			saveColumns.push(lockedColumns[i]);
	                		}
	                		for(var i in normalColumns){
	                			normalColumns[i].locked = false;
	                			saveColumns.push(normalColumns[i]);
	                		}
	                		DSYGrid.localStorageByColumns(saveColumns,saveItemId);
	                	}
	            	}else{
	            		if(ct.grid.isLocalStorage &&  DSYGrid.getLocalStorageFlag(ct.grid.getColumns())){
	            			DSYGrid.localStorage(ct.grid);
	            		}
	            	}
				}
			},
			columnshow: function ( ct, column, eOpts ) {
				if(ct.enableColumnHide){
					if(ct.grid.ownerGrid.enableLocking){
	            		var saveColumns = new Array();
	                	if(ct.grid.ownerGrid.isLocalStorage && DSYGrid.getLocalStorageFlag(ct.grid.ownerGrid.columns)){
	                		var lockedColumns = ct.grid.ownerGrid.lockedGrid.getColumns();
	                		var normalColumns = ct.grid.ownerGrid.normalGrid.getColumns();
	                		var saveItemId = ct.grid.ownerGrid.itemId;
	                		for(var i in lockedColumns){
	                			saveColumns.push(lockedColumns[i]);
	                		}
	                		for(var i in normalColumns){
	                			normalColumns[i].locked = false;
	                			saveColumns.push(normalColumns[i]);
	                		}
	                		DSYGrid.localStorageByColumns(saveColumns,saveItemId);
	                	}
	            	}else{
	            		if(ct.grid.isLocalStorage &&  DSYGrid.getLocalStorageFlag(ct.grid.getColumns())){
	            			DSYGrid.localStorage(ct.grid);
	            		}
	            	}
				}
			},
		}
	};
	if (q_issum == 1) {
		config.features = [ {
			ftype : 'summary',
			remoteRoot : 'summary',
			dock : summaryPosstion,
		} ];
	}

	if (unit != 0) {
		config.tbar = [ '->', '->', '->', '->', '->', '->', '->', {
			xtype : "label",
			text : "金额单位：",
			width : 65
		}, {
			xtype : 'form',
			padding : '0 0 0 0',
			width : 70,
			layout : 'fit',
			border : false,
			items : [ {
				xtype : "combobox",
				name : "unitSelect",
				margin : '0 0 0 0',
				store : unitStore,
				queryMode : 'local',
				editable : false,
				allowBlank : false,
				value : unit,
				displayField : 'name',
				valueField : 'abbr',
				listeners : {
					/*
					 * change : function( self, newValue, oldValue, eOpts ){
					 * reloadStore(); },
					 */
					select : function(combo, record, eOpts) {
						unit = record.get("abbr");
						reloadStore(false);
					}
				}
			} ]
		} ];
	}
	var dataGrid = DSYGrid.createGrid(config);
	return dataGrid;
};

function postSubmitForm(url, params, gridColumns, title, date, unit) {
	params["gridColumns"] = Ext.util.JSON.encode(gridColumns);
	var temp_form = document.createElement("form");
	temp_form.action = url;
	temp_form.target = "_blank";
	temp_form.method = "post";
	temp_form.style.display = "none";
	for ( var x in params) {
		var opt = document.createElement("textarea");
		opt.name = x;
		opt.value = "";
		// 传入后台参数值 对null和undefined做特殊处理
		if (params[x] != null && params[x] != undefined) {
			if (x == "gridColumns") {
				opt.value = params[x];
			} else if(x == "condition"){
				opt.value = encode64(encodeURI(params[x]))
			}else {
				opt.value = encodeURI(params[x]);
			}
		}
		temp_form.appendChild(opt);
	}
	document.body.appendChild(temp_form);
	temp_form.submit();
}

var items = [ {
	xtype : 'button',
	text : '查询',
	itemId : 'report_query_search',
	icon : '/report/image/sysbutton/search.png',
	handler : function(btn) {
		reloadStore(false);
	}
}, {
	xtype: 'button',
	text: '重置',
	hidden: true,
	itemId : 'report_query_reset',
	icon: '/report/image/sysbutton/cancel.png',
	handler: function () {
		var form = Ext.ComponentQuery.query('form#condition')[0];
		form.reset();
		reloadStore(false);
	}
},{
	xtype : 'button',
	text : '导出',
	name : 'export',
	disabled : true,
	icon : '/report/image/sysbutton/export.png',
	handler : function(btn) {
		DSYGrid.exportExcelClick('reportQueryGrid' + q_code, {
			exportExcel : true,
			url : '/sys-report/reportQueryExport',
			param : {
				q_title : q_title,
				deep : deep,
				exportLevel : exportLevel,
				is_sum: q_issum
			},
			listeners : {
				'beforeclick' : function(gridConfig) {
					var grid = DSYGrid.getGrid('reportQueryGrid' + q_code).getStore();
					if (grid.totalCount == 0) {
						return false;
					}
					var conditionData = grid.getProxy().extraParams;
					var flag = false;
					var count = 0;
					Ext.Ajax.request({
						method : 'POST',
						url : "/sys-report/getReportExportTime",
						params : {
							q_id : q_id,
							code : code,
							condition : encode64(q_select_condition),
							conditionData : encode64(Ext.util.JSON.encode([ conditionData ])),
							exportLevel : exportLevel
						},
						async : false,
						success : function(response, options) {
							var respText = Ext.util.JSON.decode(response.responseText);
							var times = respText.time;
							count = respText.count;
							var loopCount = respText.loopCount;
							// 创建进度条
							progressShow(count, times, loopCount);
							flag = true;
						},
						failure : function(response, options) {
							Ext.MessageBox.minWidth = 120;
							Ext.Msg.alert('提示', '获取信息失败！');
						}
					});
					var unit_name = "";
					if (unit != 0) {
						var unitValue = Ext.ComponentQuery.query('combobox[name="unitSelect"]')[0].getValue();
						if (unitValue == 100000000) {
							unit_name = "亿元";
						} else if (unitValue == 10000) {
							unit_name = "万元";
						} else if (unitValue == 1) {
							unit_name = "元";
						}
						unit_name = "单位：" + unit_name;
					}

					gridConfig.exportExcel.param = $.extend({}, gridConfig.exportExcel.param, {
						count : count,
						unit_name : unit_name
					});
					var sorter = DSYGrid.getGrid('reportQueryGrid' + q_code).getStore().getSorters().items[0];
					if (sorter) {
						gridConfig.exportExcel.param = $.extend({}, gridConfig.exportExcel.param, {
							sort : sorter.config.property,
							dir : sorter.config.direction
						});
					}
					return flag;
				}
			}
		}, function(response) {
			try{
				if (!response.contentDisposition) {
					closeProgressShow = true;
					setTimeout(function () {
						Ext.Msg.alert('提示', !!response.errMessage ? response.errMessage : '导出失败！');
						setTimeout(function () {
							closeProgressShow = false;
						}, 500);
					}, 1000);
				} else {
					Ext.MessageBox.hide();
					closeProgressShow = true;
					setTimeout(function () {
						closeProgressShow = false;
					}, 1000);
					saveLog(q_title, 'BUTTON', q_title + '导出成功');
				}
			}catch (e){
			}
		},
		function(response, options) {
			Ext.Msg.alert('提示', '导出失败！');
		});
	}

}, {
	xtype : 'button',
	text : '打印',
	name : 'print',
	disabled : true,
	icon : '/report/image/sysbutton/print.png',
	handler : function() {
		var form = Ext.ComponentQuery.query('form#condition')[0];
		var data = form.getValues();
		data["q_id"] = q_id;
		data["code"] = code;
		data["condition"] = q_select_condition;
		data["tableTitle"] = q_title;
		data["rownumberer"] = rownumberer;
		var unit_name = "";
		if (unit != 0) {
			var unitValue = Ext.ComponentQuery.query('combobox[name="unitSelect"]')[0].getValue();
			data["unit"] = unitValue;
			if (unitValue == 100000000) {
				unit_name = "亿元";
			} else if (unitValue == 10000) {
				unit_name = "万元";
			} else if (unitValue == 1) {
				unit_name = "元";
			}
			unit_name = "金额单位：" + unit_name;
		}
		data["tableUnit"] = unit_name;
		var headerLeft = "";
		var headerCenter = "";
		var headerRight = "";
		var footerLeft = "";
		var footerCenter = "";
		var footerRight = "";
		if (printConfig) {
			var tempPrint = printConfig.split('#');
			if (tempPrint.length >= 2) {
				var printFooter = tempPrint[1];
				var tempPrintFooter = printFooter.split('-');
				footerLeft = tempPrintFooter[0];
				if (tempPrintFooter.length >= 2) {
					footerCenter = tempPrintFooter[1];
				}

				if (tempPrintFooter.length >= 3) {
					footerRight = tempPrintFooter[2];
				}
			}
			var printHeader = tempPrint[0];
			var tempPrintHeader = printHeader.split('-');
			headerLeft = tempPrintHeader[0];
			if (tempPrintHeader.length >= 2) {
				headerCenter = tempPrintHeader[1];
			}

			if (tempPrintHeader.length >= 3) {
				headerRight = tempPrintHeader[2];
			}
		}
		var printSet = [ {
			header_left : headerLeft,
			header_center : headerCenter,
			header_right : headerRight,
			footer_left : footerLeft,
			footer_center : footerCenter,
			footer_right : footerRight
		} ];
		data["printSet"] = Ext.util.JSON.encode(printSet);
		// data["tableDate"]=encodeURI("截止日期：2017-7-7");
		// gridColumns=DSYGrid.getGrid('reportQueryGrid'+q_code).headerConfig.headerJson;
		var sorter = DSYGrid.getGrid('reportQueryGrid' + q_code).getStore().getSorters().items[0];
		if (sorter) {
			data["sort"] = sorter.config.property;
			data["dir"] = sorter.config.direction;
		}
		// 解决打印时候没有添加上Authorization的问题
		// postSubmitForm("/report/sys-manage/printGridData", data, columns);
		data["gridColumns"] = Ext.util.JSON.encode(columns);
		printPublicFiles('/sys-report/printGridData','POST',data)
	}
}, {
	xtype : 'button',
	text : '关闭',
	itemId : 'report_query_close',
	icon : '/report/image/sysbutton/cancel.png',
	handler : function(btn) {
		btn.up('panel').close();
		window.close();
		// window.parent.close();
	}
}, {
	xtype : 'button',
	text : '报表说明',
	itemId : 'report_query_remark',
	icon : '/report/image/sysbutton/message.png',
	handler : function(btn) {
		// 弹出弹出框
		Ext.create('Ext.window.Window', {
			title : '报表说明', // 窗口标题
			width : 700, // 窗口宽度
			height : 360, // 窗口高度
			layout : 'fit',
			maximizable : true,
			itemId : 'window_remark_info', // 窗口标识
			buttonAlign : 'right', // 按钮显示的位置
			modal : true, // 模式窗口，弹出窗口后屏蔽掉其他组件
			closeAction : 'destroy',// hide:单击关闭图标后隐藏，可以调用show()显示。如果是destroy，则会将window销毁。
			items : [ {
				xtype : 'form',
				width : '100%',
				height : '100%',
				itemId : 'window_query_remark_panel',
				layout : 'column',
				autoScroll : true,
				defaultType : 'textareafield',
				defaults : {
					margin : '5 10 5 10',
					columnWidth : .99,
					labelWidth : 94
				// 控件默认标签宽度
				},
				items : [ {
					height : '95%',
					value : qRemark
				} ]

			} ]

		}).show();
	}
}, {
	xtype : 'button',
	// text: gnsqName,
	hidden : true,
	itemId : 'report_query_gnsq',
	// icon: '/report/image/sysbutton/cancel.png',
	handler : function(btn) {
		if (iflfptmof == 1) {
			menuOnClick(gnsqName, gnsqUrl)
		}
	}
}, '->', initButton_Screen(), {
	xtype : 'button',
	text : '返回',
	hidden: true,
	itemId : 'report_query_return',
	icon : '/report/image/sysbutton/cancel.png',
	handler : function(btn) {
		var userAgent = navigator.userAgent;
		if (userAgent.indexOf("MSIE") > 0) {
			if (navigator.userAgent.indexOf("MSIE 6.0") > 0) {
				window.opener = null;
				window.close();
			} else {
				window.open('', '_top');
				window.top.close();
			}
		} else if (userAgent.indexOf("Firefox") != -1 || userAgent.indexOf("Presto") != -1) {
			window.location.replace("about:blank");
		} else if (userAgent.indexOf("Html5Plus") > 0) {
			window.history.back();
		} else {
			window.opener = null;
			window.open("", "_self");
			window.close();
		}
		if (typeof window.parent.removeTab != 'undefined') {
			window.parent.removeTab('mainTabPanel');
		} else if (typeof window.parent.parent.removeTab != 'undefined') {
			window.parent.removeTab('mainTabPanel');
		}
	}
}, {
	xtype : 'tbspacer',
	itemId : 'report_query_sql',
	width : 20,
	height : '100%',
	listeners : {
		afterrender : function(self) {
			if (sqlDebug == "1") {
				$(self.el.dom).click(function() {
					// 弹出弹出框
					Ext.create('Ext.window.Window', {
						title : '报表查询sql', // 窗口标题
						width : 700, // 窗口宽度
						height : 360, // 窗口高度
						layout : 'fit',
						maximizable : true,
						itemId : 'window_notice_info', // 窗口标识
						buttonAlign : 'right', // 按钮显示的位置
						modal : true, // 模式窗口，弹出窗口后屏蔽掉其他组件
						closeAction : 'destroy',// hide:单击关闭图标后隐藏，可以调用show()显示。如果是destroy，则会将window销毁。
						items : [ {
							xtype : 'form',
							width : '100%',
							height : '100%',
							itemId : 'window_querysql_panel',
							layout : 'column',
							autoScroll : true,
							defaultType : 'textareafield',
							defaults : {
								margin : '5 10 5 10',
								columnWidth : .99,
								labelWidth : 94
							// 控件默认标签宽度
							},
							items : [ {
								height : '95%',
								value : querySql

							} ]

						} ]

					}).show();
				});
			}
		}
	}
} ];
function getPage(page) {
	var pageFlag = true;
	if ('0' == page) {
		pageFlag = false;
	}
	return pageFlag;
}
function conditionConf(condition, q_condition, paramShow) {
	if (condition != null && condition.length > 0) {
		Ext.Array.forEach(condition, function(str) { // 单纯的遍历数组
			var cId = str.C_ID;
			var model = str.C_DATA_MODEL;
			var source = str.C_DATA_SOURCE;
			var value = str.C_DATA_VALUE;
			// C_DATATYPE
			var dispmode = str.C_DISP_MODE;
			var fieldcode = str.C_CODE;
			var fieldtitle = str.C_TITLE;
			// var labelwidth = str.C_LABEL_WIDTH;
			var tips = str.C_TIPS;
			// var width = str.C_WIDTH;
			var ismust = str.IS_MUST_INPUT;
			var ismul = str.IS_MUL;
			var srccode = str.C_SRC_ID;
			var conditionIsRight = str.IS_RIGHT;
			var hiddenFlag = false;
			var isShow = str.IS_SHOW;
			var isLeaf = str.IS_LEAF;
			var isRootShow = str.IS_ROOT_SHOW;
			var isDependentFlag = false;// 是否有依赖，默认没有依赖
			if (srccode) {
				isDependentFlag = true;
				//关联条件有多个的处理
				var srcCodeList = srccode.split(",");
				// 如果当前组件有级联关系,添加进数组,后续统一进行赋值处理
                for (var i = 0; i < condition.length; i++) {
					for (var j = 0; j < srcCodeList.length; j++) {
						var srcCode = srcCodeList[j];
						if (condition[i].C_CODE === srcCode) {
							var valueCondition = condition[i].C_DATA_VALUE;
							if (!isNull(q_condition[srcCode])){
								valueCondition = q_condition[srcCode];
							}
							relationConditionArr.push({
								name: srcCode,
								xtype: condition[i].C_DISP_MODE,
								value: valueCondition
							});
						}
					}
                }
			}
			for ( var key in q_condition) {
				if (fieldcode.toUpperCase() == key.toUpperCase()) {
					if (paramShow == 0) {
						hiddenFlag = true;
					}
					value = q_condition[key];
					break;
				}
			}
			if (isShow == 0) {
				hiddenFlag = true;
			}
			if ('treecombobox' == dispmode) {
				conditionItems.push({
					xtype : 'treecombobox',
					fieldLabel : fieldtitle,
					name : fieldcode,
					maxPickerHeight : 270,
					displayField : 'name',
					valueField : 'id',
					rootVisible : isRootShow == "1" ? true : false,
					lines : false,
					selectModel : getLeafFlag(isLeaf),
					checkModel : getMulFlag(ismul),
					multiSelect : true,
					value : value,
					hidden : hiddenFlag,
					srccode : srccode,
					isRight : conditionIsRight,
					margin : '2 5 2 6',
					padding : '0 0 0 0',
					editable : true,
					allowBlank : isMustPut(ismust),
					emptyText : !!value ? "" : tips,
					rootUse : getRootFlag(ismul),
					store : DebtQueryTreeStore(cId, {
						isRight : conditionIsRight,
						isMul : ismul,
						isDependent : isDependentFlag
					}, ismul),
					listeners : {
						change : function(self, newValue) {
							var conditionPanel = Ext.ComponentQuery.query('form#condition')[0];
							conditionPanel.items.each(function(item, index, length) {
								if (item.srccode && item.name != self.name) {
									var srcFlag = false;
									var srcIds = item.srccode.split(',');
									for ( var i = 0; i < srcIds.length; i++) {
										if (self.name.trim() == srcIds[i].trim()) {
											srcFlag = true;
											break;
										}
									}
									if (srcFlag) {
										var xtype = item.xtype;
										var name = item.name;
										var target = Ext.ComponentQuery.query(xtype + '[name="' + name + '"]')[0];
										var targetValue = item.value;
										var linkValue = self.getValue();
										if (xtype == "treecombobox" || xtype == "combobox") {
											target.getStore().getProxy().extraParams[self.name.trim()] = linkValue;
											target.getStore().load({
												callback : function(records, operation, success) {
													if (records.length == 1) {
														if (xtype == "treecombobox") {
															if(records[0].childNodes && records[0].childNodes.length > 0){
																target.setValue('');
															}else{
																target.setValue(records[0].get("code"));
															}
														}else{
															target.setValue(records[0].get("code"));
														}
													} else {
														if (xtype == "treecombobox") {
															//target.setValue('');
														} else {
															var dataFlag = false;
															for ( var i = 0; i < records.length; i++) {
																var code = records[i].get("code");
																if (code == targetValue) {
																	dataFlag = true;
																	break;
																}
															}
															if (dataFlag) {
																target.setValue(targetValue);
															} else {
																target.setValue('');
															}
														}
													}
												}
											});
										} else if (xtype == "textfield") {
											target.setValue('');
											if (linkValue) {
												$.post('/getTextFieldValue', {
													q_id : q_id,
													c_code : item.name,
													target : self.name.trim() + "#" + linkValue,
												}, function(data) {
													if (data.targetValue) {
														target.setValue(data.targetValue);
													}
												}, 'JSON');

											}
										}
									}
								}
							});
						}
					}
				});
			} else if ('combobox' == dispmode) {
				conditionItems.push({
					xtype : "combobox",
					fieldLabel : fieldtitle,
					name : fieldcode,
					// store: DebtOlapEleStoreTable(source),
					store : comboboxStore(model, cId, conditionIsRight, source),
					queryMode : 'local',
					value : value,
					hidden : hiddenFlag,
					srccode : srccode,
					isRight : conditionIsRight,
					displayField : 'name',
					valueField : 'code',
					margin : '2 5 2 6',
					padding : '0 0 0 0',
					emptyText : !!value ? "" : tips,
					allowBlank : isMustPut(ismust),
					editable : false,// 禁用编辑
					listeners : {
						// 由于下拉框组件初始化赋值未触发change事件,因此手动赋值触发事件
                        afterrender: function (self) {
                            for (var i = 0; i < relationConditionArr.length; i++) {
                                var conditionName = relationConditionArr[i].name;
                                var conditionType = relationConditionArr[i].xtype;
                                var conditionValue = relationConditionArr[i].value;
                                if (self.name === conditionName && self.xtype === conditionType) {
                                    Ext.ComponentQuery.query(conditionType + '[name="' + conditionName + '"]')[0].setValue(conditionValue);
                                }
                            }
                        },
						change : function(self, newValue, oldValue, eOpts) {
							var conditionPanel = Ext.ComponentQuery.query('form#condition')[0];
							conditionPanel.items.each(function(item, index, length) {
								if (item.srccode && item.name != self.name) {
									var srcFlag = false;
									var srcIds = item.srccode.split(',');
									for ( var i = 0; i < srcIds.length; i++) {
										if (self.name.trim() == srcIds[i].trim()) {
											srcFlag = true;
											break;
										}
									}
									if (srcFlag) {
										var xtype = item.xtype;
										var name = item.name;
										var target = Ext.ComponentQuery.query(xtype + '[name="' + name + '"]')[0];
										var targetValue = item.value;
										var linkValue = self.getValue();
										if (xtype == "treecombobox" || xtype == "combobox") {
											target.getStore().getProxy().extraParams[self.name.trim()] = linkValue;
											target.getStore().load({
												callback : function(records, operation, success) {
													if (records.length == 1) {
														if (xtype == "treecombobox") {
															if(records[0].childNodes && records[0].childNodes.length > 0){
																target.setValue('');
															}else{
																target.setValue(records[0].get("code"));
															}
														}else{
															target.setValue(records[0].get("code"));
														}
													} else {
														if (xtype == "treecombobox") {
															//target.setValue('');
														} else {
															var dataFlag = false;
															for ( var i = 0; i < records.length; i++) {
																var code = records[i].get("code");
																if (code == targetValue) {
																	dataFlag = true;
																	break;
																}
															}
															if (dataFlag) {
																target.setValue(targetValue);
															} else {
																target.setValue('');
															}
														}
													}
												}
											});
										} else if (xtype == "textfield") {
											target.setValue('');
											if (linkValue) {
												$.post('/getTextFieldValue', {
													q_id : q_id,
													c_code : item.name,
													target : self.name.trim() + "#" + linkValue,
												}, function(data) {
													if (data.targetValue) {
														target.setValue(data.targetValue);
													}
												}, 'JSON');

											}

										}
									}
								}
							});
						}
					}
				});
			} else if ('textfield' == dispmode) {
				conditionItems.push({
					xtype : "textfield",
					fieldLabel : fieldtitle,
					name : fieldcode,
					value : value,
					hidden : hiddenFlag,
					srccode : srccode,
					margin : '2 5 2 6',
					padding : '0 0 0 0',
					emptyText : tips,
					allowBlank : isMustPut(ismust),
					enableKeyEvents : true,
					listeners : {
						'keydown' : function(self, e, eOpts) {
							var key = e.getKey();
							if (key == Ext.EventObject.ENTER) {
								reloadStore(false);
							}
						}
					}
				});
			} else if ('datefield' == dispmode) {
				conditionItems.push({
					xtype : "datefield",
					fieldLabel : fieldtitle,
					name : fieldcode,
					// width:width,
					// labelWidth: labelwidth,
					value : value,
					hidden : hiddenFlag,
					format : 'Y-m-d',
					margin : '2 5 2 6',
					padding : '0 0 0 0',
					emptyText : tips,
					allowBlank : isMustPut(ismust)
				});
			} else if ('label' == dispmode) {
				conditionItems.push({
					xtype : "textfield",
					fieldLabel : "附加条件",
					name : fieldcode,
					columnWidth : 0.64,
					editable : false,// 禁用编辑
					// html: '<div
					// style="width:400px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;">'+value+'</div>',
					value : value,
					hidden : hiddenFlag,
					margin : '2 5 2 6',
					padding : '0 0 0 0'
				});
			} else if ('numberfield' == dispmode) {
				conditionItems.push({
					xtype : "numberfield",
					fieldLabel : fieldtitle,
					name : fieldcode,
					value : value,
					hidden : hiddenFlag,
					margin : '2 5 2 6',
					padding : '0 0 0 0',
					emptyText : tips,
					allowBlank : isMustPut(ismust)
				});
			}
		});
	}

	// 如果给下拉框组件新赋的值与初始化值一致,也不会触发change事件,因此在此处将有级联关系的父级初始化值置为空
    for (var i = 0; i < conditionItems.length; i++) {
        for (var j = 0; j < relationConditionArr.length; j++) {
            // 如果当前组件是级联父级并且类型是combobox(只有combobox初始化时需要手动触发change事件)
            if (conditionItems[i].name === relationConditionArr[j].name && relationConditionArr[j].xtype === "combobox") {
                conditionItems[i].value = "";
            }
        }
    }

	return conditionItems;
};

function comboboxStore(model, cId, conditionIsRight, source) {
	if (!source) {
		return EleStoreEnum(model);
	}
	return getQueryStrore(cId, {
		isRight : conditionIsRight
	});
};

function getLeafFlag(isLeaf) {
	var selectModel = 'all';
	if (isLeaf == 1) {
		selectModel = 'leaf';
	}
	return selectModel;
}

function getMulFlag(ismul) {
	var checkModel = 'single';
	if (ismul == 1) {
		checkModel = 'multi';
	}
	return checkModel;
};
function getRootFlag(ismul) {
	var rootFlag = true;
	if (ismul == 0) {
		rootFlag = false;
	}
	return rootFlag;
};
function isMustPut(ismust) {
	var flag = true;
	if ("1" == ismust) {
		flag = false;
	}
	return flag;
};

function fieldConf(colArray) {
	if (colArray == null || colArray.length <= 0) {
		return;
	}
	columns = new Array();
	var col_length = colArray.length;
	var i = 0;
	if (rownumberer) {
		// 如果显示行号,第一列设置为rownumberer
		col_length++;
		i++;
		columns[0] = {
			xtype : 'rownumberer',
			dataIndex : 'rownumberer',
			header : '',
			text : '',
			align : 'center',
			width : 50,
			summaryType : 'count',
			summaryRenderer : function() {
				return '合计';
			}
		};
		for (; i < col_length; i++) {
			deepcount = 1;
			// 列显示行号
			var col = colArray[i - 1];
			columns[i] = configColumn(col);
			if (col.columns && col.columns.length > 0) {
				childColumns(columns[i], col.columns, deepcount);
			}
		}
	} else {
		for (; i < col_length; i++) {
			deepcount = 1;
			// 列显示行号
			var col = colArray[i];
			columns[i] = configColumn(col);
			if (col.columns && col.columns.length > 0) {
				childColumns(columns[i], col.columns, deepcount);
			}
		}
	}

	return columns;
};

function childColumns(rootColumn, childColumns, deepcount) {
	deepcount++;
	var child = new Array();
	for ( var i = 0; i < childColumns.length; i++) {
		child[i] = configColumn(childColumns[i]);
		if (childColumns[i].columns && childColumns[i].columns.length > 0) {
			arguments.callee(child[i], childColumns[i].columns, deepcount);
		} else {
			if (deepcount > deep) {
				deep = deepcount;
			}
		}
	}
	rootColumn.columns = child;
}

function configColumn(col) {
	// fieldCode fieldTitle fieldType dataType dataTable fieldLength
	/*
	 * DATA_SORT DATA_TYPE DATA_URL FIELD_CODE FIELD_LENGTH FIELD_TITLE
	 * FIELD_TYPE IS_SUM IS_SHOW IS_URL_PARAM URL_TYPE IS_NEWLINE DATA_URL_FIELD
	 */
	var column = {};
	column.is_merge = col.IS_MERGE;
	column = {
		header : col.FIELD_TITLE,// 设置标题文字
		type : col.FIELD_TYPE == null ? "string" : col.FIELD_TYPE, // 设置列解析类型
		text : col.FIELD_TITLE,// 设置标题文字
		dataIndex : col.FIELD_CODE,// 设置列字段
		hidden : col.IS_SHOW == "0" ? true : false
	};
	column.width = parseInt(col.FIELD_LENGTH) == 0 ? 100 : parseInt(col.FIELD_LENGTH);// 设置固定列宽;
	column.style = '{text-align: center;}';
	column.summaryRenderer = function(value, data, dataIndex) {
		return value;
	};
	// titleAlign
	// 默认列渲染类型为字符型
	// 设置列渲染类型为数字型，右对齐
	if (col.FIELD_TYPE == "int" || col.fieldType == "number") {
		column.align = "right";
		column.xtype = "numbercolumn";
		column.summaryType = "sum";
		column.format = "0";
		column.summaryRenderer = function(value, data, dataIndex) {
			return Ext.util.Format.number(value, '0,000');
		};
	} else if (col.FIELD_TYPE == "float") {
		column.align = "right";
		column.xtype = "numbercolumn";
		if (!isNull(col.FIELD_FORMAT)) {
			column.format = col.FIELD_FORMAT;
		}
		column.summaryType = "sum";
		column.summaryRenderer = function(value, data, dataIndex) {
			// var totalCount
			// =DSYGrid.getGrid('reportQueryGrid').getStore().totalCount;
			// if(totalCount == 0){
			// value = 0;
			// }
			if (!isNull(col.FIELD_FORMAT)) {
				return Ext.util.Format.number(value, col.FIELD_FORMAT);
			} else {
				return Ext.util.Format.number(value, '0,000.00');
			}
		};
	} else if (col.FIELD_TYPE == "rstring") {
		column.type = "string";
		column.align = "right";
	} else if (col.FIELD_TYPE == "numberstr") {
		column.align = "right";
		column.type = "string";
		column.summaryType = "sum";
		if (!isNull(col.FIELD_FORMAT)) {
			column.format = col.FIELD_FORMAT;
		}
		column.summaryRenderer = function (value, data, dataIndex) {
			if (!isNull(col.FIELD_FORMAT)) {
				return Ext.util.Format.number(value, col.FIELD_FORMAT);
			} else {
				return Ext.util.Format.number(value, '0,000.##');
			}
		};
	}
	if (col.FIELD_CODE) {
		if ((col.FIELD_CODE.toUpperCase()) == 'BUSIID') {
			column.align = "center";
		}
	}
	if (col.IS_LOCK == 1) {
		column.locked = true;
	}
	if (col.IS_NEWLINE == 1) {
		// is_newline[col.FIELD_CODE] = col.IS_NEWLINE;
		column.cellWrap = true;
	}
	if (col.IS_URL_PARAM == 1) {
		urlParam.push(col.FIELD_CODE);
	}
	if (!isNull(col.DATA_URL) || !isNull(col.DATA_URL_FIELD)) {
		if (!isNull(col.DATA_URL_FIELD)) {
			url_field[col.FIELD_CODE] = col.DATA_URL_FIELD;
		} else {
			if (!isNull(col.DATA_URL)) {
				url[col.FIELD_CODE] = col.DATA_URL;
			}
		}
		urlType[col.FIELD_CODE] = col.URL_TYPE;
	}
	if (!isNull(col.DATA_URL) || col.IS_NEWLINE == 1 || !isNull(col.DATA_URL_FIELD)) {

		column.renderer = function(value, cell, record, rowIndex, colIndex, store, view) {

			var headerCt = this.getHeaderContainer(), column = headerCt.getHeaderAtIndex(colIndex);
			var colname = column.dataIndex;
			// if(is_newline[colname] == 1){
			// cell.style = 'white-space:normal;word-break:break-all;';
			if (url[colname] == null && url_field[colname] == null) {
				return value;
			}
			// }

			if (url[colname] != null || url_field[colname] != null) {

				var cururl;
				if (url_field[colname] != null) {
					var urlfield = url_field[colname];
					cururl = record.get(urlfield);
				} else {
					cururl = url[colname];
				}
				if (cururl == null || "" == cururl) {
					return value;
				}
				if (cururl.indexOf("?") > 0) {
					cururl = cururl + "&";
				} else {
					cururl = cururl + "?";
				}
				var tran = "";
				for ( var i in urlParam) {
					if ("" == tran) {
						if (urlParam[i].toUpperCase() == 'BUSIID') {
							if (record.get(urlParam[i].toUpperCase()) != null
									&& record.get(urlParam[i].toUpperCase()) != "") {
								var bus = record.get(urlParam[i].toUpperCase()).split('-');
								tran = urlParam[i] + "=" + bus[0];
							}
						} else {
							tran = urlParam[i] + "=" + record.get(urlParam[i].toUpperCase());
						}
					} else {
						if (urlParam[i].toUpperCase() == 'BUSIID') {
							if (record.get(urlParam[i].toUpperCase()) != null
									&& record.get(urlParam[i].toUpperCase()) != "") {
								var bus = record.get(urlParam[i].toUpperCase()).split('-');
								tran = tran + "&" + urlParam[i] + "=" + bus[0];
							}
						} else {
							tran = tran + "&" + urlParam[i] + "=" + record.get(urlParam[i].toUpperCase());
						}
					}
				}
				//去掉传参的双引号
				tran = tran.replaceAll('"','');
				if ((colname.toUpperCase()) == 'BUSIID') {
					if (value == null || value == "") {
						return value;
					} else {
						var values = value.split('-');
						var showValue = values[1];
						if (showValue == 1) {
							showValue = "";
						}
						return '<a href = "#" onclick ="showwindows(\''
								+ cururl
								+ tran
								+ '\')"><img src="/report/image/sysbutton/fujian.png" width="13px" height="11px" title="查看附件"  />'
								+ showValue + '</a>';
					}
				}
				if (urlType[colname] == 1) {
					//添加上超链接时候数字不处理千分位
					if(col.FIELD_TYPE=="float"||col.FIELD_TYPE == "int" || col.fieldType == "number"){
						if (!isNull(col.FIELD_FORMAT)) {
							return '<a href = "#" onclick ="showwindows(\'' + cururl + tran + '\')">' + Ext.util.Format.number(value,col.FIELD_FORMAT) + '</a>';
						} else {
							return '<a href = "#" onclick ="showwindows(\'' + cururl + tran + '\')">' + Ext.util.Format.number(value,'0,000.00') + '</a>';
						}
					}else{
						if(value=="合计"){
							return value
						}else{
							return '<a href = "#" onclick ="showwindows(\'' + cururl + tran + '\')">' + value + '</a>';
						}
					}
					// <a
					// onclick="window.open('webpage.asp','_self');void
					// 0" href="#"> 点击这里 </a>
					// window.open("Webpage.asp?","height=100,width=100,status=yes,toolbar=yes,
					// menubar=no,location=no");
					
					// return '<a onclick="window.open();" href="#">' +
					// value + '</a>';
					// return value;
				} else {
					//添加上超链接时候数字不处理千分位
					if(col.FIELD_TYPE=="float"||col.FIELD_TYPE == "int" || col.fieldType == "number"){
						if (!isNull(col.FIELD_FORMAT)) {
							return '<a href = "#" onclick ="menuOnClick(\'' + col.FIELD_TITLE + '穿透\',\'' + cururl + tran
							+ '\')">' +Ext.util.Format.number(value,col.FIELD_FORMAT) + '</a>'
						} else {
							return '<a href = "#" onclick ="menuOnClick(\'' + col.FIELD_TITLE + '穿透\',\'' + cururl + tran
							+ '\')">' +Ext.util.Format.number(value,'0,000.00') + '</a>'
						}
					}else{
						if(value=="合计"){
							return value
						}else{
							// TODO 2024-07-18 针对特殊字段OLD_PRO_NAME，并且项目ID，申报ID为空时，不添加项目穿透链接
							if (['OLD_PRO_NAME'].includes(col.FIELD_CODE) && !record.data.APPLYID && !record.data.PROID) {
								return value
							}
							return '<a href = "#" onclick ="menuOnClick(\'' + col.FIELD_TITLE + '穿透\',\'' + cururl + tran
								+ '\')">' + value + '</a>';
						}
						
					}
					
					// return '<a href="' + cururl +tran + '"
					// target="_blank" style="color:#3329ff;">' + value
					// + '</a>';
				}
			}
		};
	} else {
		column.renderer = function(value, cell, record, rowIndex, colIndex, store, view) {			
			var headerCt = this.getHeaderContainer(),
        	colname = headerCt.getHeaderAtIndex(colIndex).dataIndex;
        	if(compare && colname != "YWSJ_SM"){				
        		ywsjid = headerCt.getHeaderAtIndex(0).dataIndex;				   					
				if(ywsjid == "YWSJID"){
					var nextRecord = store.getAt(rowIndex+1);
					if(nextRecord){
						ywsjidValue = record.get("YWSJID"),
						nextYwsjidValue = nextRecord.get("YWSJID");
						if(ywsjidValue == nextYwsjidValue){
							var nextValue = nextRecord.get(colname);
							if(value != nextValue){
								cell.tdCls="alarm_colour_red";
							}								
						}
					}	
					var previousRowIndex = rowIndex-1;
					if(previousRowIndex >= 0){
						var previousRecord = store.getAt(previousRowIndex);
						previousYwsjidValue = previousRecord.get("YWSJID");
						if(ywsjidValue == previousYwsjidValue){
							var previousValue = previousRecord.get(colname);
							if(value != previousValue){
								cell.tdCls="alarm_colour_red";
							}								
						}
					}
				}		
			}			
			if (col.FIELD_TYPE == "string" || col.FIELD_TYPE == "rstring") {
				if (value && isSpaceTrans != "0") {
					value = value.replace(/\s/g, "&nbsp;");
				}
			} else if (col.FIELD_TYPE == "int" || col.fieldType == "number") {
				value = Ext.util.Format.number(value, '0,000');
			} else if (col.FIELD_TYPE == "float") {
				if (!isNull(col.FIELD_FORMAT)) {
					value = Ext.util.Format.number(value, col.FIELD_FORMAT);
				} else {
					value = Ext.util.Format.number(value, '0,000.00');
				}
			}
			return value;
		};
	}
	return column;
}

function reloadGrid() {
	var formFlag = false;
	var formData = {};
	Ext.Array.forEach(condition, function(str) { // 单纯的遍历数组
		var value = str.C_DATA_VALUE;
		var fieldcode = str.C_CODE;
		var ismust = str.IS_MUST_INPUT;
		for ( var key in q_condition) {
			if (fieldcode.toUpperCase() == key.toUpperCase()) {
				value = q_condition[key];
			}
		}
		if (!isMustPut(ismust)) {
			if (!value) {
				formFlag = true;
				return false;
			}
		}
		if (!value) {
			value = "";
		}
		formData[fieldcode] = value;
	});
	if (formFlag) {
		saveLog(q_title, 'BUTTON', q_title + '未执行查询，存在隐藏必录条件！');
		return;
	}
	var grid = DSYGrid.getGrid('reportQueryGrid' + q_code);
	var store = grid.getStore();
	if (unit != 0) {
		unit = Ext.ComponentQuery.query('combobox[name="unitSelect"]')[0].getValue();
		store.getProxy().extraParams["unit"] = unit;
	}
	store.getProxy().extraParams["condition"] = encode64(q_select_condition);
	store.getProxy().extraParams["q_id"] = q_id;
	store.getProxy().extraParams["code"] = code;
	store.getProxy().extraParams["rownumberer"] = rownumberer;
	Ext.apply(store.proxy.extraParams, formData);
	var startD = new Date();
	store.loadPage(1, {
		callback : function(records, operation, success) {
			if (operation['_response']) {
				querySql = Ext.util.JSON.decode(operation['_response'].responseText).sql;
				if (querySql && querySql.indexOf('sql错误') > 0) {
					var endD = new Date();
					var useD = (endD.getTime() - startD.getTime()) / 1000;
					useD = numberFormat(useD, 2, 1);
					saveLog(q_title, 'BUTTON', q_title + '报表查询失败，耗时：' + useD + "秒");
				} else {
					var endD = new Date();
					var useD = (endD.getTime() - startD.getTime()) / 1000;
					useD = numberFormat(useD, 2, 1);
					saveLog(q_title, 'BUTTON', q_title + '报表查询成功，耗时：' + useD + "秒");
				}
				var totalcount = parseInt(Ext.util.JSON.decode(operation['_response'].responseText).totalcount);
				var store = DSYGrid.getGrid('reportQueryGrid' + q_code).getStore();
				if (!!!orderCheck) {
					orderCheck = 100000;
				}
				if (totalcount > orderCheck) {
					store.setRemoteSort(false);
				} else {
					store.setRemoteSort(true);
				}

				//如果没有数据不允许导出
				if(totalcount > 0 ){
					Ext.ComponentQuery.query('button[name="export"]')[0].setDisabled(false);
					Ext.ComponentQuery.query('button[name="print"]')[0].setDisabled(false);
				}else{
					Ext.ComponentQuery.query('button[name="export"]')[0].setDisabled(true);
					Ext.ComponentQuery.query('button[name="print"]')[0].setDisabled(true);
				}

			} else {
				saveLog(q_title, 'BUTTON', q_title + '报表查询超时');
			}
		}
	})
}

/**
 * 加载表格数据
 * @param isopenrun 是否打开即查询
 */
function reloadStore(isopenrun) {
	var formData = {};
	var form = Ext.ComponentQuery.query('form#condition')[0];
	if (isopenrun) {
		var formFlag = false;
		Ext.Array.forEach(condition, function(str) { // 单纯的遍历数组
			var value = str.C_DATA_VALUE;
			var fieldcode = str.C_CODE;
			var ismust = str.IS_MUST_INPUT;
			for ( var key in q_condition) {
				if (fieldcode.toUpperCase() == key.toUpperCase()) {
					value = q_condition[key];
				}
			}
			if (!isMustPut(ismust)) {
				if (!value) {
					formFlag = true;
					return false;
				}
			}
			if (!value) {
				value = "";
			}
			formData[fieldcode] = value;
		});
		if (formFlag) {
			saveLog(q_title, 'BUTTON', q_title + '未执行查询，存在隐藏必录条件！');
			return;
		}
	} else {
		Ext.ComponentQuery.query('button#report_query_search')[0].setDisabled(true);
		if (!form.isValid()) {
			saveLog(q_title, 'BUTTON', q_title + '未执行查询，存在隐藏必录条件！');
			Ext.ComponentQuery.query('button#report_query_search')[0].setDisabled(false);
			return;
		}
		formData = form.getForm().getFieldValues();
		formData = $.extend({}, formData, form.getValues());
	}
	var queryMap = {};
	Ext.Ajax.request({
		method : 'POST',
		url : "/sys-report/getReportQueryHeader",
		params : {
			code : code,
			detailForm : encode64(Ext.util.JSON.encode([ formData ]))
		},
		async : false,
		success : function(response, options) {
			// // 获取返回的JSON，并根据gridid，获取表头配置信息
			var respText = Ext.util.JSON.decode(response.responseText);
			q_title = respText.qTitle;
			fieldList = eval(respText.fieldList);
			printConfig = respText.print_config;
			queryMap = eval(respText.queryMap);
			// conditionConf(condition,q_condition,paramShow);
			fieldConf(fieldList);
		},
		failure : function(response, options) {
			Ext.MessageBox.minWidth = 120;
			Ext.Msg.alert('提示', '获取报表头信息失败！');
		}
	});
	var gridPanel = Ext.ComponentQuery.query('panel#reportQueryGridPanel')[0];
	gridPanel.removeAll(true);
	gridPanel.add(initGridPanel());
	Ext.defer(function(){
		var grid = DSYGrid.getGrid('reportQueryGrid' + q_code);
		grid.setTitle('<span class="header-font">' + q_title + '</span>');
		var store = grid.getStore();
		if (unit != 0) {
			unit = Ext.ComponentQuery.query('combobox[name="unitSelect"]')[0].getValue();
			store.getProxy().extraParams["unit"] = unit;
		}
		store.getProxy().extraParams["condition"] = encode64(q_select_condition);
		store.getProxy().extraParams["q_id"] = q_id;
		store.getProxy().extraParams["code"] = code;
		store.getProxy().extraParams["rownumberer"] = rownumberer;
		store.getProxy().extraParams["export_data_format"] = queryMap ? (queryMap.EXPORT_DATA_FORMAT ? queryMap.EXPORT_DATA_FORMAT :"") : "";
		var new_params = formData;
		Ext.apply(store.proxy.extraParams, new_params);
		// store.load();
		var startD = new Date();
		//每次查询前清空配置项，防止表头高度变化
		window.gridConfig = null;
		//加载数据数据前记录表头高度
		beforeReloadGridHead();
		//加载数据数据前记录表头高度
		grid.on("afterrender", function () {
			beforeReloadGridHead();
		});
		grid.on("afterlayout", function () {
			//加载数据数据前记录表头高度
			beforeReloadGridHead();
			//加载数据完成后重置表头高度,保持与查询前一致
			reloadGridHead();
		});
		store.loadPage(1, {
			callback : function(records, operation, success) {
				//加载数据完成后重置表头高度,保持与查询前一致
				reloadGridHead();
				//添加判断，当后台有返回值时才进行操作
				if(operation['_response']){
					var message = Ext.util.JSON.decode(operation['_response'].responseText).message;
					if (message) {
						Ext.Msg.alert('提示', message);
					} else {
						querySql = Ext.util.JSON.decode(operation['_response'].responseText).sql;
						if (querySql && querySql.indexOf('sql错误') > 0) {
							var endD = new Date();
							var useD = (endD.getTime() - startD.getTime()) / 1000;
							useD = numberFormat(useD, 2, 1);
							saveLog(q_title, 'BUTTON', q_title + '报表查询失败，耗时：' + useD + "秒");
						} else {
							var endD = new Date();
							var useD = (endD.getTime() - startD.getTime()) / 1000;
							useD = numberFormat(useD, 2, 1);
							saveLog(q_title, 'BUTTON', q_title + '报表查询成功，耗时：' + useD + "秒");
						}
						var totalcount = parseInt(Ext.util.JSON.decode(operation['_response'].responseText).totalcount);
						var store = DSYGrid.getGrid('reportQueryGrid' + q_code).getStore();
						if (!!!orderCheck) {
							orderCheck = 100000;
						}
						if (totalcount > orderCheck) {
							store.setRemoteSort(false);
						} else {
							store.setRemoteSort(true);
						}
	
						//如果没有数据不允许导出
						if(totalcount > 0 ){
							Ext.ComponentQuery.query('button[name="export"]')[0].setDisabled(false);
							Ext.ComponentQuery.query('button[name="print"]')[0].setDisabled(false);
						}else{
							Ext.ComponentQuery.query('button[name="export"]')[0].setDisabled(true);
							Ext.ComponentQuery.query('button[name="print"]')[0].setDisabled(true);
						}
	
					}
				}else{
					saveLog(q_title, 'BUTTON', q_title + '报表查询超时');
				}
				Ext.ComponentQuery.query('button#report_query_search')[0].setDisabled(false);
			}
		})
	},10,this)
	
	// ,columns );
	// store.loadPage(1,{
	// callback: function(records, operation, success) {
	// querySql=Ext.util.JSON.decode(operation['_response'].responseText).sql;
	// if(querySql.indexOf('sql错误') > 0){
	// var endD = new Date();
	// var useD = (endD.getTime()-startD.getTime())/1000;
	// useD = numberFormat(useD,2,1);
	// saveLog(q_title,'BUTTON',q_title+'报表查询失败，耗时：'+useD+"秒");
	// }else{
	// var endD = new Date();
	// var useD = (endD.getTime()-startD.getTime())/1000;
	// useD = numberFormat(useD,2,1);
	// saveLog(q_title,'BUTTON',q_title+'报表查询成功，耗时：'+useD+"秒");
	// }
	// }
	// })

};

function progressShow(count, times, loopCount) {
	if (count == 0 || closeProgressShow) {
		return;
	}
	Ext.MessageBox.show({
		msg : '共导出' + count + '条数据，预计耗时' + times + '秒',
		title : '请耐心等待...',
		progressText : '正在导出...',
		width : 400,
		progress : true,
		closable : false,
		animateTarget : '导出'
	});
	var i = 0;
	var fn = function() {
		++i;
		var useTime = i;
		var hasTime = times - useTime;
		if (i === times) {
			Ext.MessageBox.hide();
			if (!closeProgressShow) {
				Ext.MessageBox.wait('正在导出，请耐心等待...', '请等待');
			}
		} else if (closeProgressShow) {
			Ext.MessageBox.hide();
		} else {
			var val = i / times;
			Ext.MessageBox.updateProgress(val, Math.round(100 * val) + '% completed', '共导出' + count + '条数据，预计耗时'
					+ hasTime + '秒');
			setTimeout(fn, 1000);
		}
	};
	setTimeout(fn, 1000);
};

function toggleTopHidden() {
	var conditionPanel = Ext.ComponentQuery.query('form#condition')[0];
	var conditionHeader = Ext.ComponentQuery.query('header#condition_header')[0];
	if (upFlag) {
		conditionHeader.setHidden(true);
		if (conditionPanel) {
			conditionPanel.setHidden(true);
		}
		upFlag = false;
		$('img.img-collapsible').attr('src', '/report/image/sysbutton/down.png');
	} else {
		conditionHeader.setHidden(false);
		if (conditionPanel) {
			conditionPanel.setHidden(false);
		}
		upFlag = true;
		$('img.img-collapsible').attr('src', '/report/image/sysbutton/up.png');
	}
}

function initButton_Screen() {
	return {
		xtype : 'button',
		text : '全屏',
		name : 'screen',
		hidden:true,
		icon : '/report/image/sysbutton/fullscreen.png',
		handler : function() {
			//var url = requestUrl + "?";
			//for ( var key in q_condition) {
				//url = url + "&" + key + "=" + q_condition[key];
			//}
			//url = url + "&condition=" + q_select_condition;
			//urlSplit(url);
			window.open(window.location.href);
		}
	};
}

function saveLog(action_name, log_type, remark, log_level, menu_code, menu_name, menu_url) {
	if (action_name == undefined || action_name == null || action_name == "") {
	} else {
		if (log_level == undefined || log_level == null || log_level == "") {
			log_level = '0';
		}
		if (log_type == undefined || log_type == null || log_type == "") {
			log_type = "BUTTON";
		}
		if (menu_code == undefined || menu_code == null || menu_code == "") {
			menu_code = menuCode;
		}
		if (menu_url == undefined || menu_url == null || menu_url == "") {
			menu_url = requestUrl + "?";
			for ( var key in q_condition) {
				menu_url = menu_url + "&" + key + "=" + q_condition[key];
			}
			menu_url = menu_url + "&condition=" + q_select_condition;
		}
	}
}

/**
 * 加载数据前，重置表格表头高度前，获取表头与body位置和高度
 */
function beforeReloadGridHead() {
    if (!window.gridConfig || !window.gridConfig.bodyTop) {
        var grid = DSYGrid.getGrid('reportQueryGrid' + q_code);
        if (!!grid && !!grid.getEl() && !!grid.getEl().dom) {
            var gridbody = $(grid.getEl().dom).find('div.x-grid-body');
            var gridhead = $(grid.getEl().dom).find('div.x-grid-header-ct');
            var height = $(gridbody[0]).innerHeight();
            var headheight = $(gridhead[0]).innerHeight();
            var top = $(gridbody[0]).position().top;
            var headtop = $(gridhead[0]).position().top;
            if (top <= 0) {
                return;
            }
            window.gridConfig = {bodyHeight: height, bodyTop: top, headHeight: headheight, headTop: headtop};
        }
    }
}

/**
 * 加载数据后重置表格表头高度
 */
function reloadGridHead() {
    if (window.gridConfig && window.gridConfig.bodyTop) {
        //重新定位表格body，修改其高度
        var grid = DSYGrid.getGrid('reportQueryGrid' + q_code);
        var gridbody = $(grid.getEl().dom).find('div.x-grid-body');
        var top = $(gridbody[0]).position().top;
        //如果body位置与查询前一致，不修改表头与body位置
        if (window.gridConfig.bodyTop == top) {
            return;
        }
        $(gridbody[0]).css('top', window.gridConfig.bodyTop);
        $(gridbody[0]).height(window.gridConfig.bodyHeight);
        //修改表格body内部box高度
        var gridbodyInner = $(grid.getEl().dom).find('div.x-grid-body').find('div.x-grid-view');
        $(gridbodyInner[0]).height($(gridbody[0]).innerHeight());

        //重新修改表头高度
        var gridhead = $(grid.getEl().dom).find('div.x-grid-header-ct');
        $(gridhead[0]).height(window.gridConfig.headHeight);
        //修改表头内部box高度，保持一致
        var gridhead_box = $(gridhead).children('div.x-box-inner');
        $(gridhead_box[0]).height($(gridhead[0]).innerHeight());
        loopChild(gridhead);
    }
}

/**
 * 级联循环，修改列元素及其子级高度
 * @param els
 */
function loopChild(els) {
    for (var i = 0; i < els.length; i++) {
        var el = els[i];
        //当前列元素子级下部行高度=当前列高度-当前列子级上部行高度
        var child_box = $(el).children('div.x-box-inner');
        var child_inner = $(el).children('div.x-column-header-inner');
        if (child_inner.length > 0 && child_box.length > 0) {
            //当前列元素子级下部行高度=当前列高度-当前列子级上部行高度
            $(child_box[0]).height($(el).innerHeight() - $(child_inner[0]).outerHeight());
        } else if (child_inner.length > 0 && child_box.length <= 0) {
            //当前列元素子级下部行高度=当前列高度,当不存在多行时
            $(child_box[0]).height($(el).innerHeight());
        }
        if ($(child_box).children('div.x-box-target').length > 0) {
            //当前列下部行如果有子级列元素，保持高度一致
            // -1为减去边框高度，每个列元素，都只有上边框与右边框
            var child_col = $(child_box[0]).children('div.x-box-target').children('div.x-column-header');
            $(child_col).height($(child_box[0]).innerHeight() - 1);
            //级联修改子级列元素内部高度
            loopChild(child_col)
        }
    }

}
